package com.aliyun.oss.UserService.impl;

import com.aliyun.oss.Constants.Constants;
import com.aliyun.oss.UserMapper.WxUserLoginMapper;
import com.aliyun.oss.UserService.WxUserService;
import com.aliyun.oss.pojo.Entity.WxUser;
import com.aliyun.oss.pojo.Vo.WxUserVO;
import com.aliyun.oss.utils.GetNowTime;
import com.aliyun.oss.utils.HttpClientUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

@Service
public class WxUserServiceImpl extends ServiceImpl<WxUserLoginMapper, WxUser> implements WxUserService {
    @Autowired
    WxUserLoginMapper wxUserLoginMapper;
//    网络发送类
    @Autowired
    HttpClientUtil httpClientUtil;
//    申请openId地址
    public static final String WX_LOGIN="https://api.weixin.qq.com/sns/jscode2session";
    @Override
    public WxUserVO wxLogin(String code) throws JsonProcessingException {
        String openid = getOpenId(code);

//        判断openId是否为空，如果为空表示登录失败，抛出异常
        if(openid==null){
            throw new RuntimeException("登录失败");
        }
//        判断当前用户是否是新用户,根据openid判断是否是新用户
        WxUser wxUser = wxUserLoginMapper.selectOne(new QueryWrapper<WxUser>().eq("openid", openid));



//        是则自动注册，否则查询返回
        if (wxUser==null){
            wxUser = new WxUser();
            wxUser.setOpenid(openid);
            LocalDateTime nowTime = GetNowTime.getNowTime();
            wxUser.setCreateTime(nowTime);
            wxUserLoginMapper.insert(wxUser);
            return new WxUserVO(wxUser.getId(),openid,null);
        }else{
            return new WxUserVO(wxUser.getId(),openid,null);
        }

    }
    private String getOpenId(String code) throws JsonProcessingException {
        //        调用微信接口服务，获取当前微信用户的openId
        Map<String, String> map=new HashMap<>();
        map.put("appid", Constants.APP_ID);
        map.put("secret",Constants.SECRET);
        map.put("js_code",code);
        map.put("grant_type","authorization_code");
        String string = httpClientUtil.doGet(WX_LOGIN, map, null);
//        System.out.println("openId"+string);
        ObjectMapper objectMapper = new ObjectMapper();
        JsonNode jsonNode = objectMapper.readTree(string);
//        判断openId是否为空
        if(jsonNode.get("openid")==null){
            throw new RuntimeException("登录失败");
        }
        String openid = jsonNode.get("openid").asText();
        return openid;
    }
}
